package com.twb.easyExcel.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.support.ExcelTypeEnum;

/**
 * @ClassName EasyExcelToFileUtil
 * @Description easyexl导出到压缩包的的工具类
 * @author DHL
 * @date 2021年8月11日 上午11:30:57
 */
@SuppressWarnings("all")
public class EasyExcelToFileUtil {

	protected static Logger log = LoggerFactory.getLogger(EasyExcelToFileUtil.class);

	/**
	 * @Title exlport
	 * @Description 根据表头，数据，文件名称，进行exl的导出，xls格式
	 * @param fileName 文件名
	 * @param filepath 标题
	 * @param alldata  实际数据
	 * @param cls
	 * @return
	 * @author DHL
	 * @date 2021年8月11日 上午11:31:52
	 */
	public static String exlport(String fileName, String filePath, List<List<Object>> allData, Class<? extends BaseRowModel> cls) {
		return exportFile(fileName, filePath, allData, ".xlsx", ExcelTypeEnum.XLSX, cls);
	}

	private static String exportFile(String fileName, String filePath, List<List<Object>> allData, String filetype, ExcelTypeEnum exltype, Class<? extends BaseRowModel> cls) {
		FileOutputStream fos = null;
		String filesPathResult = "";
		try {
			filesPathResult = filePath + fileName + getNowTime() + filetype;
			// 如果文件夹不存在就创建文件夹
			File folder = new File(filePath);
			if (!folder.exists() && !folder.isDirectory()) {
				folder.mkdirs();
			}
			File file = new File(filesPathResult);
			if (!file.exists()) {
				file.createNewFile();
			}
			fos = new FileOutputStream(file);
			ExcelWriter writer = EasyExcelFactory.getWriter(fos, exltype, true);

			// 动态添加表头，适用一些表头动态变化的场景
			com.alibaba.excel.metadata.Sheet sheet1 = new com.alibaba.excel.metadata.Sheet(1, 0, cls);
			sheet1.setSheetName("sheet1");
			// 写数据
			writer.write1(allData, sheet1);
			// 将上下文中的最终 outputStream 写入到指定文件中
			writer.finish();
		} catch (Exception e) {
			log.error("导出exl失败" + fileName, e);
		} finally {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return filesPathResult;
	}

	private static String getNowTime() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String dateString = formatter.format(new Date());
		return dateString;
	}
}
